package com.kaishengit.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.kaishengit.entity.Project;
import com.kaishengit.entity.User;
import com.kaishengit.entity.UserProject;
import com.kaishengit.service.ProService;
import com.kaishengit.service.UserService;
import com.kaishengit.util.PKutil;
import com.kaishengit.util.Page;

public class ProjectServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private ProService  service = new ProService();
	private User user=new User();
	private UserService  userService = new UserService ();
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
			request.setCharacterEncoding("utf-8");
			String method = request.getParameter("method");
			if(method == null || "".equals(method)){
				list(request,response);
			}else if("new".equals(method)){
				save(request,response);
			}else if("toNew".equals(method)){
				create(request,response);
			}else if("enter".equals(method)){
				enter(request,response);
			}else if("addUser".equals(method)){
				String httpMethod = request.getMethod();
				if("GET".equals(httpMethod)) {
					toAdd(request,response);
				} else if("POST".equals(httpMethod)) {
					add(request,response);
				}
			}else if("editUser".equals(method)){
				String httpMethod = request.getMethod();
				if("GET".equals(httpMethod)) {
					toEdit(request,response);
				} else if("POST".equals(httpMethod)) {
					edit(request,response);
				}
			}
	}
	
	/**
	 * 将修改后的信息保存进数据库
	 * @throws IOException 
	 * */
	private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userid=request.getParameter("id");
		user=getFormInformation(request);
		userService.update(userid,user);
		response.sendRedirect("project.jspx");
		
	}
	
	/**
	 * 进入到修改用户信息edit_user页面
	 *
	 * */
	private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session= request.getSession();
		User us=(User) session.getAttribute("user");
		String id=us.getId();
		User user=userService.findById(id);
		request.setAttribute("user", user);
		request.getRequestDispatcher("WEB-INF/views/edit_user.jsp").forward(request, response);
	}
	

	/**
	 * 将新用户的信息保存进数据库
	 * @throws IOException 
	 * */
	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		user=getFormInformation(request);
		userService.save(PKutil.getPk(),user);
		response.sendRedirect("project.jspx");
	}

	/**
	 * 进入到添加新用户new_user页面
	 * 
	 * */
	private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/views/new_user.jsp").forward(request, response);
	}
	
	/**
	 * 上传图片的表单获取
	 * */
	public User getFormInformation(HttpServletRequest request) throws IOException{
		File uploadfile = new File("c:/imgupload");
		File temp = new File("c:/imgtemp");
		if(!uploadfile.exists()){
			uploadfile.mkdir();
		}
		if(!temp.exists()){
			temp.mkdir();
		}
		if(ServletFileUpload.isMultipartContent(request)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024*10);
			factory.setRepository(temp);
			ServletFileUpload uploader = new ServletFileUpload(factory);
			uploader.setFileSizeMax(1024*1024*10);
			try {
				List<FileItem> list = uploader.parseRequest(request);
				
				for(FileItem item : list) {
					if(item.isFormField()) {
						if("name".equals(item.getFieldName())) {
							String username=item.getString();
							user.setUsername(username);
						}else if("password".equals(item.getFieldName())) {
							String password=item.getString();
							user.setPassword(password);
						}
					} else {
						String oldname = item.getName();
						String extendName = oldname.substring(oldname.lastIndexOf("."));
						String newName = PKutil.getPk()+ extendName;
						user.setImgname(newName);
						InputStream stream = item.getInputStream();
						
						FileOutputStream outputStream = new FileOutputStream(new File(uploadfile,newName));
						byte[] buffer = new byte[1024];
						int len = -1;
						while((len = stream.read(buffer)) != -1) {
							outputStream.write(buffer, 0, len);
						}
						outputStream.flush();
						outputStream.close();
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
		return user;
	}


	/**
	 * 进入到project.jsp显示页面的servlet
	 * 
	 * */
	private void enter(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String projectid=request.getParameter("id");
		HttpSession session= request.getSession();
		User user=(User) session.getAttribute("user");
		UserProject up=service.findById(user.getId(),projectid);
		session.setAttribute("userProject", up);
		session.setAttribute("projectid",projectid);
		response.sendRedirect("pro.jspx");
			
	}
	

	/**
	 * 进入到创建项目new_project页面
	 * 
	 * */
	
	private void create(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<User> userlist=userService.findAll();
		request.setAttribute("userlist", userlist);
		request.getRequestDispatcher("WEB-INF/views/new_project.jsp").forward(request, response);
	}
	
	

	/**
	 * 将项目保存进数据库
	 *
	 * */
	private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String projectname=request.getParameter("projectname");
		String content=request.getParameter("content");
		String manager=request.getParameter("manager");
		String member=request.getParameter("members");
		service.save(projectname,content,manager,member);
		response.sendRedirect("project.jspx");
	}
	
	/**
	 *进入到main.jsp页面
	 * */
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String p = request.getParameter("p");
		String q = request.getParameter("q");
		int pageNum =0;
		if(p == null || "".equals(p)){
			pageNum = 1;
		}else{
			pageNum = Integer.valueOf(p);
		}
		
		int PpageNum =0;
		if(q == null || "".equals(q)){
			PpageNum = 1;
		}else{
			PpageNum = Integer.valueOf(q);
		}
		HttpSession session= request.getSession();
		User user=(User) session.getAttribute("user");
		String userid=user.getId();
		Page<UserProject> list = service.findAllByProjectId(pageNum,userid);
		Page<Project> Plist = service.findAll(PpageNum);
		List<Project> projectlist=service.findAll(user);
		session.setAttribute("projectlist", projectlist);
		request.setAttribute("userProjectList",list);
		request.setAttribute("Plist",Plist);
		request.getRequestDispatcher("WEB-INF/views/main.jsp").forward(request, response);
	}
}
